package k.b.s;

import k.b.s.model.*;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;


import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;


public class ChannelXmlHelper {
	private static ChannelXmlHelper channelXmlHelper = new ChannelXmlHelper();

	/**
	 * This class is singleton.
	 */
	private ChannelXmlHelper() {
	}

	/**
	 * インスタンスの取得。
	 *
	 * @return このクラスのインスタンス
	 */
	public static ChannelXmlHelper getInstance() {

		return channelXmlHelper;
	}



	public ChannelRowModel parseSax(String xml, String http) {
		InputStream is = null;
		try {
			is = new ByteArrayInputStream(xml.getBytes());
			return parseSax(is, http);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(is!=null){
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}


	public ChannelRowModel parseSax(InputStream xml, String http){
		SAXParserFactory saxParaser = SAXParserFactory.newInstance();
		SaxHandler sh = null;
		try{
			SAXParser sp = saxParaser.newSAXParser();
			sh = new SaxHandler();
			sp.parse(xml,sh);

		}catch(Exception e){
			e.printStackTrace();
		}
		sh.channelRowModel.setChannel(http);
		return sh.channelRowModel;
	}


	class SaxHandler extends DefaultHandler {
		ChannelRowModel channelRowModel = new ChannelRowModel();

		boolean isChannel;
		boolean isTitle;
		boolean isDescription;
		boolean flagFinish = false;
		String title = null;
		String description = null;

		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {

			if(!flagFinish){
				if ("channel".equals(localName)) {
					isChannel = true;
				}
				if (isChannel) {
					if ("title".equals(localName)){
						isTitle = true;
					}
					if ("description".equals(localName)){
						isDescription = true;
					}
				}
			}
		}

		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException {
				channelRowModel.setTitle(title);
				channelRowModel.setDescription(description);
		}




		@Override
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			if (isChannel) {
				if (isTitle) {
					title = new String(ch,start,length);
					isTitle = false;
				}
				if (isDescription) {
					description = new String(ch, start, length);
					isDescription = false;
					flagFinish = true;
				}
			}
		}
	}
}
